<?php

namespace app\store\model;

use app\common\library\helper;
use app\common\model\BaseModel;
use think\Cache;
use think\Db;

/**
 * 问卷分类模型
 * Class Category
 * @package app\store\model
 */
class QaType extends BaseModel
{
    protected $autoWriteTimestamp  = 'datetime';
    /**
     * 获取所有分类(树状结构)
     * @return mixed
     */
    public static function getCacheTree()
    {
        return self::getALL()['tree'];
    }

    /**
     * 所有分类
     * @return mixed
     */
    public static function getALL()
    {
        $wwid = self::$wxapp_id;
        $all = Db::name('qa_type')->where(['qt_delete'=>0, 'wxapp_id'=>$wwid])->order('qt_sort asc,qt_id asc')->select();
        $tree =  self::buildTree($all);
        $data = [
            'tree'=>$tree,
            'all'=>$all
        ];
        return $data;
    }

    public static function buildTree($array, $parentId = 0) {
        $tree = [];
    
        foreach ($array as $item) {
            if ($item['qt_pid'] == $parentId) {
                $children = self::buildTree($array, $item['qt_id']);
                if ($children) {
                    $item['child'] = $children;
                }
                $tree[] = $item;
            }
        }
    
        return $tree;
    }
}